﻿Partial Public Class ItemMasterExplorer


    Public imExplorer As IMExplorerNodeInfo
    Private SpecValueGuid As String
    Private SpecValueStr As String

    Public PL_IMSpecRevDetail As PL.MESSDK.ItemMasterSpecificationRevisionDetail_PL = Nothing
    Public PL_RoutingRevDetail As SystemBoxSDK.PL.MESSDK.RoutingRevisionDetail_PL = Nothing
    Public PL_BOMRevDetail As SystemBoxSDK.PL.MESSDK.BOMRevisionDetail_PL = Nothing
    Public PL_ItemMasterRevision As SystemBoxSDK.PL.MESSDK.ItemMasterRevision_PL



    Public Overrides Sub MergeMetaQueryResult()
        Dim aChildMQ As MetaQuery = Nothing

        Try
            MainMetaQuery = MetaQuery.GetMetaQueryByName(QueryName)
            If MainMetaQuery IsNot Nothing Then
                MainMetaQuery.FillResultQuery()
                DataSrc = MainMetaQuery.ResultQuery
                AQueryList.Add(QueryName, "0")
                aChildQueryToDisplay = MainMetaQuery.GetChildDisplayQuery()

                If aChildQueryToDisplay IsNot Nothing Then
                    For Each row As DataRow In aChildQueryToDisplay.Rows
                        AQueryList.Add(row("Queryname").ToString, row("MetaqueryLevel").ToString)
                        aChildMQ = MetaQuery.GetMetaQueryByName(row("QueryName").ToString)

                        If aChildMQ IsNot Nothing Then

                            'Filtrer selon la Security par Site
                            If AppManager.SiteAccessList IsNot Nothing Then
                                If Not String.IsNullOrWhiteSpace(aChildMQ.SQLWhereContext) Then
                                    aChildMQ.SQLWhereContext += " AND "
                                End If
                                aChildMQ.SQLWhere = String.Format("SiteID in ( '00000000-0000-0000-0000-000000000000',{0})", AppManager.SiteAccessList)
                            End If

                        End If

                        aChildMQ.FillResultQuery()

                        If aChildMQ.ResultQuery.Rows.Count > 0 Then
                            DataSrc.Merge(aChildMQ.ResultQuery, False, MissingSchemaAction.Ignore)
                        End If


                    Next
                End If
            Else
                MessageWindow.ShowMessage(String.Format("refer to administrator , MetaQuery < {0} > is not functionning as expected ", QueryName), MsgBoxStyle.Exclamation)

            End If
        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        End Try
    End Sub


    Public Overrides Sub LoadContextMenu()
        MyBase.LoadContextMenu()
        imExplorer = New IMExplorerNodeInfo(NodeDataRow)
        ExplorerContextMenu()

        imExplorer.Dispose()
    End Sub

    Public Sub MetaControlActionOptionListLoad() Implements IExplorer.MetaActionOptionListLoad
        Dim action As CommonExt.Base.ActionOption

        ''Root (Level 0)


        'Todo : BDesjardins 2014-06-04 
        'action = New ActionOption("IM1", "ACT_00mmm", "Add New Site", AddressOf MenuNewSite, True, True, "1")
        'TreeActionOptionList.Add(action)

        'Root Level
        action = New ActionOption("IM0", "ACT_00094", "Add New Item Master", AddressOf MenuNewItemMaster, True, True, "0")
        MetaControlTreeListActionOptionList.Add(action)

        'Site (Level 1)
        action = New ActionOption("IM2", "ACT_00094", "Add New Item Master", AddressOf MenuNewItemMaster, True, True, "1") 'scope on ItemMasterID
        MetaControlTreeListActionOptionList.Add(action)

        'Item Master ITem (Level 2)
        action = New ActionOption("IM2", "ACT_00095", "Add New Item Master Revision (Empty)", AddressOf MenuNewItemMasterRevision, True, True, "2")
        MetaControlTreeListActionOptionList.Add(action)

        'Item Master Revision (Level 3)
        action = New ActionOption("IM3", "ACT_00096", "Approve Revision ", AddressOf MenuApproveItemMasterRevision, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM3", "ACT_00097", "Activate Revision", AddressOf MenuActivateItemMasterRevision, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM3", "ACT_00197", "Unactivate Revision", AddressOf MenuUnActivateItemMasterRevision, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM3", "ACT_00098", "Delete Revision", AddressOf MenuDeleteItemMasterRevision, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM4", "ACT_00099", "Copy to New Revision", AddressOf MenuCopyToNewItemMasterRevision, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM4", "ACT_00100", "Copy To Another Item Master", AddressOf MenuCopyToAnotherItemMasterRevision, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM5", "ACT_00103", "Enable Specification Editing", AddressOf MenuEnableSpecEditing, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM5", "ACT_00102", "Enable Routing Editing", AddressOf MenuEnableRoutingEditing, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM5", "ACT_00101", "Enable BOM Editing", AddressOf MenuEnableBOMEditing, True, True, "ItemMasterRevision")
        MetaControlTreeListActionOptionList.Add(action)


        'Specification Revision (Level 4)

        action = New ActionOption("IM6", "ACT_00108", "Activate Specification Revision", AddressOf MenuActivateSpecRevision, True, True, "IMSpecRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM7", "ACT_00109", "Print Specifications", AddressOf MenuPrintSpecification, True, True, "IMSpecRevision")
        MetaControlTreeListActionOptionList.Add(action)

        'BOM Revision (Level 4)
        action = New ActionOption("IM8", "ACT_00106", "Activate BOM Revision", AddressOf MenuActivateBOMRevision, True, True, "BOMRevision")
        MetaControlTreeListActionOptionList.Add(action)
        action = New ActionOption("IM9", "ACT_00190", "Print BOM", AddressOf MenuPrintBOM, True, True, "BOMRevision")
        MetaControlTreeListActionOptionList.Add(action)

        'Routing Revision (Level 4)
        action = New ActionOption("IM10", "ACT_00107", "Activate Routing Revision", AddressOf MenuActivateRoutingRevision, True, True, "RoutingRevision")
        MetaControlTreeListActionOptionList.Add(action)

        action = New ActionOption("IM11", "ACT_00191", "Print Routing", AddressOf MenuPrintRouting, True, True, "RoutingRevision")
        MetaControlTreeListActionOptionList.Add(action)

        'SpecRevisionActionOptionList = New ActionOptionList()

    End Sub


    Public Overridable Sub ExplorerContextMenu()

        Select Case imExplorer.QueryName
            Case "ItemMaster"

            Case "ItemMasterRevision"
                ItemMasterRevisionActionOptionMenu()

            Case "BOMRevision"
                ItemMasterSectionActionOptionMenu()

            Case "RoutingRevision"
                ItemMasterSectionActionOptionMenu()

            Case "IMSpecRevision"
                ItemMasterSectionActionOptionMenu()

            Case "IMBRevisionDetail"
                ItemMasterDetailActionOptionMenu()

            Case "IMRRevisionDetail"
                ItemMasterDetailActionOptionMenu()

            Case "IMSRevisionDetail"
                ItemMasterDetailActionOptionMenu()
        End Select

    End Sub


    Public Overridable Sub ItemMasterRevisionActionOptionMenu()

        If imExplorer IsNot Nothing Then
            Dim ItemActionOption As ActionOption
            Dim grpName As String = String.Empty


            For Each item As DXMenuItem In TreeContextMenu.Items
                ItemActionOption = item.Tag

                If ItemActionOption.OptionName.Equals("ACT_00096") AndAlso (imExplorer.IMRevisionApproved Or imExplorer.NodeActivated) Then
                    '"Approve Revision "
                    item.Enabled = False

                ElseIf ItemActionOption.OptionName.Equals("ACT_00097") AndAlso (Not imExplorer.IMRevisionApproved Or imExplorer.NodeActivated) Then
                    '"Activate Revision"
                    item.Enabled = False

                ElseIf ItemActionOption.OptionName.Equals("ACT_00197") AndAlso (Not imExplorer.NodeActivated) Then
                    '"UnActivate Revision"
                    item.Enabled = False

                ElseIf ItemActionOption.OptionName.Equals("ACT_00098") AndAlso (imExplorer.IMRevisionApproved OrElse imExplorer.NodeActivated) Then
                    '"Delete Revision"
                    item.Enabled = False

                ElseIf ItemActionOption.OptionName.Equals("ACT_00099") Then
                    '"Copy to New Revision"

                ElseIf ItemActionOption.OptionName.Equals("ACT_00100") Then
                    '"Copy To Another Item Master"

                ElseIf ItemActionOption.OptionName.Equals("ACT_00101") AndAlso (imExplorer.IMRevisionApproved OrElse imExplorer.NodeActivated OrElse imExplorer.BOMEnabled) Then
                    '"Enable BOM"
                    item.Enabled = False

                ElseIf ItemActionOption.OptionName.Contains("ACT_00102") AndAlso (imExplorer.IMRevisionApproved OrElse imExplorer.NodeActivated OrElse imExplorer.RoutingEnabled) Then
                    '"Enable Routing"
                    item.Enabled = False

                ElseIf ItemActionOption.OptionName.Contains("ACT_00103") AndAlso (imExplorer.IMRevisionApproved OrElse imExplorer.NodeActivated OrElse imExplorer.SpecEnabled) Then
                    '"Enable Specification"
                    item.Enabled = False

                Else
                    item.Enabled = ItemActionOption.Enabled

                End If
            Next

        End If
    End Sub

    Public Overridable Sub ItemMasterSectionActionOptionMenu()
        Dim ItemActionOption As ActionOption
        Dim grpName As String = String.Empty


        For Each item As DXMenuItem In TreeContextMenu.Items

            ItemActionOption = item.Tag

            If ItemActionOption.OptionName.Contains("ACT_00108") AndAlso imExplorer.NodeActivated Then
                item.Enabled = False

            ElseIf ItemActionOption.OptionName.Contains("ACT_00106") AndAlso imExplorer.NodeActivated Then
                item.Enabled = False

            ElseIf ItemActionOption.OptionName.Contains("ACT_00107") AndAlso imExplorer.NodeActivated Then
                item.Enabled = False



            Else
                item.Enabled = ItemActionOption.Enabled

            End If

        Next

    End Sub

    Public Overridable Sub ItemMasterDetailActionOptionMenu()
        Dim grpName As String = String.Empty

    End Sub


#Region "Handles"

    Public Overridable Sub ItemMaster_InitNewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
        Dim view As GridView = DirectCast(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()
        Using itemMaster As SystemBoxSDK.PL.MESSDK.ItemMaster_PL = New SystemBoxSDK.PL.MESSDK.ItemMaster_PL()
            itemMaster.NewRecord(row)
        End Using
    End Sub

    Public Overridable Sub ItemMasterRevision_DetailCustomRowCellEditForEditing(ByVal sender As Object, ByVal e As CustomRowCellEditEventArgs)
        Dim aDetailview As GridView = DirectCast(sender, GridView)
        Dim sqlWhere As String = String.Empty
        Dim aEdit As RepositoryItemGridLookUpEdit

        If e.Column.FieldName = "ItemMasterSpecRevDetailID_FK" Then
            sqlWhere = String.Format("ItemMasterRevID  = '{0}'", imExplorer.NodeID)

            aEdit = LOVBuilder("LOV_CS_ItemMasterSpecRevDetail", sqlWhere, Nothing, Nothing)
            aEdit.Name = "LOV_CS_ItemMasterSpecRevDetail"
            aDetailview.GridControl.RepositoryItems.Add(aEdit)
            e.RepositoryItem = aEdit
        End If
    End Sub


    Public Overridable Sub ItemMasterRevision_ProcessCurrentDetailRecord(ByVal sender As Object, e As Views.Base.ValidateRowEventArgs, ByVal index As Integer)
        Dim aView As GridView = DirectCast(sender, GridView)
        Dim aRow As System.Data.DataRow = aView.GetDataRow(e.RowHandle)

        If aRow IsNot Nothing AndAlso aRow.Table.TableName.Equals("IMClientSpecification") Then
            aRow("RoutingRevisionDetailId_FK") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "RoutingRevDetailID")
            aRow("SpecificationTestRevisionId_FK") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "SpecificationTestRevId_FK")
            aRow("Description_PRM") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "SpecDescr_PRM")
            aRow("Description_ALT") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "SpecDescr_ALT")
            aRow("Value") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "Value")
            aRow("TargetProd") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "Target")
            aRow("Minimum") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "Minimum")
            aRow("Maximum") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "Maximum")
            aRow("UnitId_FK") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "UnitID_FK")
            aRow("Method") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "Method")
            aRow("Repetition") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "Repetition")
            aRow("Compulsory") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "Compulsory")
            aRow("DisplayId_FK") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "DisplayID_FK")
            aRow("TargetFormatId_FK") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "TargetFormatID_FK")
            aRow("ResultDecimal") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "ResultDecimal")
            aRow("ResultOrder") = ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "ResultOrder")

            aRow("PrdDescr_PRM") = String.Format("{0} - {1}", ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "PrdCd"), ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "PrdDescr_PRM"))
            aRow("PrdDescr_ALT") = String.Format("{0} - {1}", ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "PrdCd"), ClientSpec_LookupView.GetRowCellValue(ClientSpec_LookupView.FocusedRowHandle, "PrdDescr_ALT"))
        End If
    End Sub

    Public Overridable Sub ItemMasterRevision_ShownDetailEditor(sender As Object, e As System.EventArgs)
        Dim detailView As GridView = DirectCast(sender, GridView)

        If detailView.FocusedColumn.FieldName = "ItemMasterSpecRevDetailID_FK" Then
            ClientSpec_LookupEdit = CType(detailView.ActiveEditor, GridLookUpEdit)
        End If
    End Sub

    Public Overridable Sub ClientSpec_LookupEdit_CloseUp(sender As Object, e As DevExpress.XtraEditors.Controls.CloseUpEventArgs) Handles ClientSpec_LookupEdit.CloseUp
        Dim alookup As GridLookUpEdit = DirectCast(sender, GridLookUpEdit)

        If alookup.Properties.ValueMember = "ItemMasterSpecRevDetailID" Then
            ClientSpec_LookupView = alookup.Properties.View
        End If
    End Sub

    Public Overridable Sub ItemMasterDocument_ShowInDesigner(ByVal sender As System.Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Const frmName As String = "COA Builder"

        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)
        Dim aRow As DataRow = view.GetFocusedDataRow()

        Dim newForm As ReportBuilder = New ReportBuilder With {.Name = frmName, .Text = frmName, .ShowIcon = True}
        Dim aMyXtraReport As MyXtraReport = New MyXtraReport()

        aMyXtraReport.DocumentTemplateID = Guid.Parse(aRow("DocumentTemplateID_FK").ToString)
        aMyXtraReport.DocumentTemplateName = aRow("Name").ToString
        aMyXtraReport.QueryID_FK = Guid.Parse(aRow("QueryID_FK").ToString)
        newForm.aMyXtraReport = aMyXtraReport

        newForm.ChooseCommandEnable = False
        newForm.ChooseReportEnable = False
        newForm.NewReportEnable = False

        newForm.Show()

        Me.Cursor = Cursors.Default
    End Sub


    Public Overridable Sub SpecRevDetail_MasterCustomRowCellEditForEditing(ByVal sender As Object, ByVal e As CustomRowCellEditEventArgs)
        Dim aDetailview As GridView = DirectCast(sender, GridView)
        Dim sqlWhere As String = String.Empty

        Dim aEdit As RepositoryItemGridLookUpEdit
        'Hack 1: scoping with MetaQuery's SQLWhere
        If e.Column.FieldName = "SpecID_FK" Then

            If aDetailview.FocusedRowHandle.Equals(GridControl.NewItemRowHandle) Then
                'Sécurtité du LOV selon l'Acces de l'utilisateur pour faire un Create
                sqlWhere = String.Format("SpecGroupID_FK IN ({0})", AppManager.GetGCCTSSecurity(IdRepository.ALLOWCREATE, IdRepository.APP_SPECIFGROUP))

            ElseIf Not aDetailview.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                'Sécurtité du LOV selon l'Acces de l'utilisateur pour faire un Update
                sqlWhere = String.Format("SpecGroupID_FK IN ({0})", AppManager.GetGCCTSSecurity(IdRepository.ALLOWUPDATE, IdRepository.APP_SPECIFGROUP))
            End If
            aEdit = LOVBuilder("LOV_SpecificationAll", sqlWhere, Nothing, Nothing)
            aEdit.Name = "LOV_SpecificationAll"
            'aDetailview.GridControl.RepositoryItems.Add(aEdit)
            e.RepositoryItem = aEdit


        ElseIf e.Column.FieldName = "Value" Then
            If Not aDetailview.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                SpecRevDetail_CreateSpecValueLOV(sender, e)
            End If
        End If

    End Sub


#End Region


#Region "IM Section"


    'BOM Detail
    Public Overridable Sub BOMRevDetail_InitNewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()
        PL_BOMRevDetail = EditPanePL
        PL_BOMRevDetail.ItemMasterID_FK = imExplorer.ItemMasterID
        PL_BOMRevDetail.BOMRevID_FK = imExplorer.NodeID
        PL_BOMRevDetail.PPrdId_FK = imExplorer.PrdID
        PL_BOMRevDetail.NewRecord(row)
    End Sub

    Public Overridable Sub BOMRevDetail_MasterRowClick(ByVal sender As Object, ByVal e As RowClickEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()

        If imExplorer.NodeActivated OrElse imExplorer.NodeActivated Then
            view.OptionsBehavior.ReadOnly = True
        Else
            If e.RowHandle < 0 Then
                view.OptionsBehavior.ReadOnly = False

            ElseIf row IsNot Nothing AndAlso Not IsDBNull(row("IsCopy")) Then
                If CBool(row("IsCopy")) Or Not imExplorer.NodeStatus.Equals(IdRepository.APP_ENTITYSTATUS_ENABLED) Then
                    view.OptionsBehavior.ReadOnly = True
                Else
                    view.OptionsBehavior.ReadOnly = False
                End If
            End If
        End If
    End Sub

    Public Overridable Sub BOMRevDetail_ContextMenuBeforePopup(sender As Object, e As EventArgs)
        Dim aMenu As GridViewMenu = CType(sender, GridViewMenu)
        Dim row As DataRow = aMenu.View.GetFocusedDataRow()

        If row IsNot Nothing Then
            Dim i As Integer = 0
            'For Each item In aMenu.Items
            While i < aMenu.Items.Count
                'If (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit")) Then

                '    If imExplorer.IMActivated OrElse Not imExplorer.BOMEnabled OrElse Not CBool(row("IsCopy")) Then
                '        aMenu.Items(i).Enabled = False
                '    End If
                'End If

                If (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit")) OrElse aMenu.Items(i).Caption.Contains("Delete") Then
                    If imExplorer.NodeActivated OrElse Not imExplorer.NodeStatus.Equals(IdRepository.APP_ENTITYSTATUS_ENABLED) Then
                        aMenu.Items(i).Enabled = False

                    ElseIf CBool(row("IsCopy")) And aMenu.Items(i).Caption.Contains("Delete") Then
                        aMenu.Items(i).Enabled = False

                    ElseIf (Not CBool(row("IsCopy")) And (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit"))) Then
                        aMenu.Items(i).Enabled = False
                    End If
                End If

                i += 1
            End While
        End If
    End Sub

    Public Overridable Sub BOMRevDetail_Limit(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()

            If aRow IsNot Nothing Then

                If CBool((aRow("IsCopy"))) Then

                    Dim BOMRevDetailID As Guid = CType(aRow("BOMRevDetailID"), Guid)
                    Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

                    Try
                        sqlcmd = MetaQuery.GetSPCmdByMetaName("BOMRevisionDetail_Limite")
                        'Match les parametres de la SP avec les colonne de la grilles
                        For Each pr As System.Data.SqlClient.SqlParameter In sqlcmd.Parameters
                            If aRow.Table.Columns.Contains(pr.SourceColumn) Then
                                sqlcmd.Parameters(pr.ParameterName).Value = aRow(pr.SourceColumn)
                            End If
                        Next
                        sqlcmd.ExecuteNonQuery()

                        'Refresh Screen
                        aGridControl.ReloadGrid()
                    Catch sqlex As System.Data.SqlClient.SqlException
                        If sqlex.Number = 50000 Then
                            MessageWindow.ShowMessage("Can't Limite this BOM since it is use for an Item Master Test.")
                        Else
                            MessageWindow.ShowMessage(sqlex)
                        End If
                    Finally
                        If sqlcmd IsNot Nothing Then
                            sqlcmd.Connection.Close()
                            sqlcmd.Dispose()
                        End If
                    End Try

                Else
                    MessageWindow.ShowMessage("No need to Limite, this BOM is not reference more than once.")
                End If

                'End If
            End If
        End If
    End Sub

    Public Overridable Sub BOMRevDetail_Revise(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()

            If aRow IsNot Nothing Then

                If CBool((aRow("IsCopy"))) Then

                    Dim RoutingRevDetailID As Guid = CType(aRow("BOMRevDetailID"), Guid)
                    Dim RoutingID As Guid = CType(aRow("BOMId"), Guid)

                    Try
                        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

                        Try
                            sqlcmd = MetaQuery.GetSPCmdByMetaName("BOMRevisionDetail_Revise")
                            'Match les parametres de la SP avec les colonne de la grilles
                            For Each pr As System.Data.SqlClient.SqlParameter In sqlcmd.Parameters
                                If aRow.Table.Columns.Contains(pr.SourceColumn) Then
                                    sqlcmd.Parameters(pr.ParameterName).Value = aRow(pr.SourceColumn)
                                End If
                            Next
                            sqlcmd.ExecuteNonQuery()
                        Catch sqlex As System.Data.SqlClient.SqlException

                        Finally
                            If sqlcmd IsNot Nothing Then
                                sqlcmd.Connection.Close()
                                sqlcmd.Dispose()
                            End If
                        End Try


                        'Refresh Screen
                        aGridControl.ReloadGrid()
                    Catch sqlex As System.Data.SqlClient.SqlException
                        If sqlex.Number = 50000 Then
                            MessageWindow.ShowMessage("Can't Revise this BOM since it is use for an Item Master Test.")
                        Else
                            MessageWindow.ShowMessage(sqlex)
                        End If
                    End Try
                End If
                'Else
                '    MessageWindow.ShowMessage("No need to Limite, this test is not reference more than once.")
                'End If
            End If
        End If
    End Sub


    'Routing Detail
    Public Overridable Sub RoutingRevDetail_InitNewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()
        PL_RoutingRevDetail = EditPanePL
        PL_RoutingRevDetail.ItemMasterID_FK = imExplorer.ItemMasterID
        PL_RoutingRevDetail.RoutingRevID_FK = imExplorer.NodeID
        PL_RoutingRevDetail.NewRecord(row)

    End Sub

    Public Overridable Sub RoutingRevDetail_MasterRowClick(ByVal sender As Object, ByVal e As RowClickEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()

        If imExplorer.NodeActivated OrElse imExplorer.NodeActivated Then
            view.OptionsBehavior.ReadOnly = True
        Else
            If e.RowHandle < 0 Then
                view.OptionsBehavior.ReadOnly = False

            ElseIf row IsNot Nothing AndAlso Not IsDBNull(row("IsCopy")) Then
                If CBool(row("IsCopy")) Or Not imExplorer.NodeStatus.Equals(IdRepository.APP_ENTITYSTATUS_ENABLED) Then
                    view.OptionsBehavior.ReadOnly = True
                Else
                    view.OptionsBehavior.ReadOnly = False
                End If
            End If
        End If
    End Sub

    Public Overridable Sub RoutingRevDetail_ContextMenuBeforePopup(sender As Object, e As EventArgs)
        Dim aMenu As GridViewMenu = CType(sender, GridViewMenu)
        Dim row As DataRow = aMenu.View.GetFocusedDataRow()

        If row IsNot Nothing Then
            Dim i As Integer = 0
            'For Each item In aMenu.Items
            While i < aMenu.Items.Count
                'If (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit")) Then

                '    If imExplorer.NodeActivated OrElse Not imExplorer.RoutingEnabled OrElse Not CBool(row("IsCopy")) Then
                '        aMenu.Items(i).Enabled = False
                '    End If
                'End If

                If (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit")) OrElse aMenu.Items(i).Caption.Contains("Delete") Then
                    If imExplorer.NodeActivated OrElse Not imExplorer.NodeStatus.Equals(IdRepository.APP_ENTITYSTATUS_ENABLED) Then
                        aMenu.Items(i).Enabled = False

                    ElseIf CBool(row("IsCopy")) And aMenu.Items(i).Caption.Contains("Delete") Then
                        aMenu.Items(i).Enabled = False

                    ElseIf (Not CBool(row("IsCopy")) And (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit"))) Then
                        aMenu.Items(i).Enabled = False
                    End If
                End If
                i += 1
            End While
        End If
    End Sub

    Public Overridable Sub RoutingRevDetail_Limit(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()

            If aRow IsNot Nothing Then

                If CBool((aRow("IsCopy"))) Then
                    Dim RoutingID As Guid = CType(aRow("RoutingId"), Guid)
                    Dim IMSpecRevDetailID As Guid = CType(aRow("RoutingRevDetailID"), Guid)

                    If RoutingRevDetail_Validation(RoutingID) Then
                        Try
                            'TODO...
                            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

                            Try
                                sqlcmd = MetaQuery.GetSPCmdByMetaName("RoutingRevisionDetail_Limite")
                                'Match les parametres de la SP avec les colonne de la grilles
                                For Each pr As System.Data.SqlClient.SqlParameter In sqlcmd.Parameters
                                    If aRow.Table.Columns.Contains(pr.SourceColumn) Then
                                        sqlcmd.Parameters(pr.ParameterName).Value = aRow(pr.SourceColumn)
                                    End If
                                Next
                                sqlcmd.ExecuteNonQuery()
                                'Fin TODO
                            Catch sqlex As System.Data.SqlClient.SqlException

                            Finally
                                If sqlcmd IsNot Nothing Then
                                    sqlcmd.Connection.Close()
                                    sqlcmd.Dispose()
                                End If
                            End Try


                            'Refresh Screen
                            aGridControl.ReloadGrid()
                        Catch sqlex As System.Data.SqlClient.SqlException
                            If sqlex.Number = 50000 Then
                                MessageWindow.ShowMessage("Can't Limite this Routing since it is use for an Item Master Test.")
                            Else
                                MessageWindow.ShowMessage(sqlex)
                            End If
                        End Try
                    Else
                        MessageWindow.ShowMessage("This Routing is link to a Specification. Please validate your product's specifications.")
                    End If

                Else
                    MessageWindow.ShowMessage("No need to Limite, this Routing is not reference more than once.")
                End If

                'End If
            End If
        End If
    End Sub

    Public Overridable Sub RoutingRevDetail_Revise(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()

            If aRow IsNot Nothing Then

                If CBool((aRow("IsCopy"))) Then

                    Dim RoutingRevDetailID As Guid = CType(aRow("RoutingRevDetailID"), Guid)
                    Dim RoutingID As Guid = CType(aRow("RoutingId"), Guid)

                    If RoutingRevDetail_Validation(RoutingID) Then
                        Try
                            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

                            Try
                                sqlcmd = MetaQuery.GetSPCmdByMetaName("RoutingRevisionDetail_Revise")
                                'Match les parametres de la SP avec les colonne de la grilles
                                For Each pr As System.Data.SqlClient.SqlParameter In sqlcmd.Parameters
                                    If aRow.Table.Columns.Contains(pr.SourceColumn) Then
                                        sqlcmd.Parameters(pr.ParameterName).Value = aRow(pr.SourceColumn)
                                    End If
                                Next
                                sqlcmd.ExecuteNonQuery()
                            Catch sqlex As System.Data.SqlClient.SqlException
                                Throw sqlex
                            Finally
                                If sqlcmd IsNot Nothing Then
                                    sqlcmd.Connection.Close()
                                    sqlcmd.Dispose()
                                End If
                            End Try


                            'Refresh Screen
                            aGridControl.ReloadGrid()
                        Catch sqlex As System.Data.SqlClient.SqlException
                            If sqlex.Number = 50000 Then
                                MessageWindow.ShowMessage("Can't Revise this Routing since it is use for an Item Master Test.")
                            Else
                                MessageWindow.ShowMessage(sqlex)
                            End If
                        End Try
                    Else
                        MessageWindow.ShowMessage("This Routing is link to a Specification. Please validate your product's specifications.")
                    End If



                End If
                'Else
                '    MessageWindow.ShowMessage("No need to Limite, this test is not reference more than once.")
                'End If
            End If
        End If
    End Sub

    Public Overridable Function RoutingRevDetail_Validation(ByVal RoutingID As Guid) As Boolean

        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRRDetail_Validate")
            sqlcmd.Parameters("@RoutingID").Value = RoutingID
            sqlcmd.Parameters("@ItemMasterRevID").Value = imExplorer.NodeID

            If sqlcmd.ExecuteReader(CommandBehavior.CloseConnection).HasRows Then
                Return False
            End If

        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Return True
    End Function

    Public Overridable Sub RoutingRevDetail_CustomRowCellEditForEditing(ByVal sender As Object, ByVal e As CustomRowCellEditEventArgs)
        Dim aView As GridView = DirectCast(sender, GridView)
        Dim aRTEdit As RepositoryItemButtonRichTextEditExt
        Dim aLov As New RepositoryItemGridLookUpEdit()

        Dim aRow As DataRow = aView.GetFocusedDataRow()

        If aView.Tag.ToString = "RoutingSheet" Then
            If Not IsNothing(aView.Columns("Instruction_PRM")) Or Not IsNothing(aView.Columns("Instruction_ALT")) Then
                If e.Column.FieldName = "Instruction_PRM" Or e.Column.FieldName = "Instruction_ALT" Then
                    aRTEdit = New RepositoryItemButtonRichTextEditExt

                    If e.CellValue Is Nothing Then
                        aRTEdit.Text = String.Empty
                    Else
                        aRTEdit.Text = e.CellValue.ToString
                    End If

                    aView.GridControl.RepositoryItems.Add(aRTEdit)
                    e.RepositoryItem = aRTEdit
                End If
            End If
        End If


    End Sub


    'Spec Detail
    Public Overridable Sub SpecRevDetail_InitNewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()
        PL_IMSpecRevDetail = EditPanePL
        PL_IMSpecRevDetail.ItemMasterID_FK = imExplorer.ItemMasterID
        PL_IMSpecRevDetail.ItemMasterSpecRevID_FK = imExplorer.NodeID
        PL_IMSpecRevDetail.NewRecord(row)
    End Sub

    Public Overridable Sub SpecRevDetail_MasterCellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)

        If e.Column.Name.Contains("Test") Then
            Dim aView As GridView = DirectCast(sender, GridView)
            Dim currentRow As DataRow = aView.GetFocusedDataRow()

            'Get SpecificationTest
            If Not String.IsNullOrEmpty(e.Value.ToString()) Then

                Dim SpecificationTestRevId As Guid = Guid.Parse(e.Value.ToString)
                Dim mqEntries As MetaQuery = MetaQuery.GetMetaQueryByName("SpecificationTestRevision")
                mqEntries.SQLWhere = String.Format("SpecificationTestRevId = '{0}'", SpecificationTestRevId)
                mqEntries.FillResultQuery()
                Dim SpecTestRow As DataRow = mqEntries.ResultQuery.Rows(0)

                'Fill Current Row Data

                If Not IsDBNull(SpecTestRow.Item("Value")) Then
                    currentRow("Value") = SpecTestRow.Item("Value").ToString
                End If

                If Not IsDBNull(SpecTestRow.Item("Target")) Then
                    currentRow("Target") = CDec(SpecTestRow.Item("Target"))
                End If

                If Not IsDBNull(SpecTestRow.Item("Minimum")) Then
                    currentRow("Minimum") = CDec(SpecTestRow.Item("Minimum"))
                End If

                If Not IsDBNull(SpecTestRow.Item("Maximum")) Then
                    currentRow("Maximum") = CDec(SpecTestRow.Item("Maximum"))
                End If

                If Not IsDBNull(SpecTestRow.Item("UnitId_FK")) Then
                    currentRow("UnitId_FK") = DirectCast(SpecTestRow.Item("UnitId_FK"), Guid)
                End If

                If Not IsDBNull(SpecTestRow.Item("SOPID_FK")) Then
                    currentRow("SOPID_FK") = DirectCast(SpecTestRow.Item("SOPID_FK"), Guid)
                End If

                If Not IsDBNull(SpecTestRow.Item("SOP")) Then
                    currentRow("SOP") = SpecTestRow.Item("SOP")
                End If

                If Not IsDBNull(SpecTestRow.Item("Average")) Then
                    currentRow("Average") = CDec(SpecTestRow.Item("Average"))
                End If

                If Not IsDBNull(SpecTestRow.Item("NmbrUtilisation")) Then
                    currentRow("NmbrUtilisation") = CDec(SpecTestRow.Item("NmbrUtilisation"))
                End If

                If Not IsDBNull(SpecTestRow.Item("Method")) Then
                    currentRow("Method") = SpecTestRow.Item("Method")
                End If

                If Not IsDBNull(SpecTestRow.Item("Repetition")) Then
                    currentRow("Repetition") = CInt(SpecTestRow.Item("Repetition"))
                End If

                If Not IsDBNull(SpecTestRow.Item("Compulsory")) Then
                    currentRow("Compulsory") = CBool(SpecTestRow.Item("Compulsory"))
                End If

                If Not IsDBNull(SpecTestRow.Item("CompulsoryRep")) Then
                    currentRow("CompulsaryRep") = CInt(SpecTestRow.Item("CompulsoryRep"))
                End If

                If Not IsDBNull(SpecTestRow.Item("ResultDecimal")) Then
                    currentRow("ResultDecimal") = CInt(SpecTestRow.Item("ResultDecimal"))
                End If

                If Not IsDBNull(SpecTestRow.Item("EquipmentTypeId_FK")) Then
                    currentRow("EquipmentTypeId_FK") = DirectCast(SpecTestRow.Item("EquipmentTypeId_FK"), Guid)
                End If

            End If
        End If

    End Sub

    Public Overridable Sub SpecRevDetail_DetailCellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)
        If e.Column.Name.Contains("SocietyId_FK") Then
            Dim detailView As GridView = DirectCast(sender, GridView)
            Dim parentView As GridView = CType(detailView.ParentView, GridView)

            Dim currentRow As DataRow = detailView.GetFocusedDataRow()
            Dim parentRow As DataRow = currentRow.GetParentRow(detailView.Name)


            currentRow("ItemMasterRevisionId_FK") = imExplorer.NodeID 'parentRow("ItemMasterRevID")
            currentRow("RoutingRevisionDetailId_FK") = parentRow("RoutingRevDetailID")
            currentRow("ItemMasterSpecRevDetailID_FK") = parentRow("ItemMasterSpecRevDetailID")
            currentRow("SpecificationTestRevisionId_FK") = parentRow("SpecificationTestRevId_FK")

            currentRow("Description_PRM") = parentRow("SpecDescr_PRM")
            currentRow("Description_ALT") = parentRow("SpecDescr_ALT")
            currentRow("TargetProd") = parentRow("Target")
            'currentRow("TargetCOA") 
            currentRow("Value") = parentRow("Value")
            currentRow("Minimum") = parentRow("Minimum")
            currentRow("Maximum") = parentRow("Maximum")
            currentRow("UnitId_FK") = parentRow("UnitId_FK")
            currentRow("Method") = parentRow("Method")
            currentRow("Repetition") = parentRow("Repetition")
            currentRow("Compulsory") = parentRow("Compulsory")
            currentRow("DisplayId_FK") = parentRow("DisplayId_FK")
            currentRow("TargetFormatId_FK") = parentRow("TargetFormatId_FK")
            currentRow("ResultDecimal") = parentRow("ResultDecimal")
            'currentRow("COADetailVisibilityId_FK") 
            currentRow("ResultOrder") = parentRow("ResultOrder")

            'ClientSpecificationId,
            'SocietyId_FK,

            'RecordVersion,
        End If
    End Sub

    Public Overridable Sub SpecRevDetail_MasterRowClick(ByVal sender As Object, ByVal e As RowClickEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()

        If imExplorer.NodeActivated OrElse imExplorer.NodeActivated Then
            view.OptionsBehavior.ReadOnly = True
        Else
            If e.RowHandle < 0 Then
                view.OptionsBehavior.ReadOnly = False

            ElseIf row IsNot Nothing AndAlso Not IsDBNull(row("IsCopy")) Then
                If CBool(row("IsCopy")) Or Not imExplorer.NodeStatus.Equals(IdRepository.APP_ENTITYSTATUS_ENABLED) Then
                    view.OptionsBehavior.ReadOnly = True
                Else
                    view.OptionsBehavior.ReadOnly = False
                End If
            End If
        End If

    End Sub

    Public Overridable Sub SpecRevDetail_ContextMenuBeforePopup(sender As Object, e As EventArgs)
        Dim aMenu As GridViewMenu = CType(sender, GridViewMenu)
        Dim row As DataRow = aMenu.View.GetFocusedDataRow()

        If row IsNot Nothing Then
            Dim i As Integer = 0
            'For Each item In aMenu.Items
            While i < aMenu.Items.Count
                'If (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit")) Then

                '    If imExplorer.NodeActivated OrElse Not imExplorer.SpecEnabled OrElse Not CBool(row("IsCopy")) Then
                '        aMenu.Items(i).Enabled = False
                '    End If
                'End If

                If (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit")) OrElse aMenu.Items(i).Caption.Contains("Delete") Then
                    If imExplorer.NodeActivated OrElse Not imExplorer.NodeStatus.Equals(IdRepository.APP_ENTITYSTATUS_ENABLED) Then
                        aMenu.Items(i).Enabled = False

                    ElseIf CBool(row("IsCopy")) And aMenu.Items(i).Caption.Contains("Delete") Then
                        aMenu.Items(i).Enabled = False

                    ElseIf (Not CBool(row("IsCopy")) And (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit"))) Then
                        aMenu.Items(i).Enabled = False
                    End If
                End If
                i += 1
            End While
        End If
    End Sub

    Public Overridable Sub SpecRevDetail_Limit(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()

            If aRow IsNot Nothing Then

                If CInt(aRow("NbReference")) > 1 Then
                    'If CBool((aRow("IsCopy"))) Then

                    Dim IMSpecRevDetailID As Guid = CType(aRow("ItemMasterSpecRevDetailID"), Guid)

                    Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

                    Try
                        sqlcmd = MetaQuery.GetSPCmdByMetaName("ItemMasterSpecificationRevisionDetail_Limite")
                        'Match les parametres de la SP avec les colonne de la grilles
                        For Each pr As System.Data.SqlClient.SqlParameter In sqlcmd.Parameters
                            If aRow.Table.Columns.Contains(pr.SourceColumn) Then
                                sqlcmd.Parameters(pr.ParameterName).Value = aRow(pr.SourceColumn)
                            End If
                        Next
                        sqlcmd.ExecuteNonQuery()
                        'Refresh Screen
                        aGridControl.ReloadGrid()

                    Catch sqlex As System.Data.SqlClient.SqlException
                        If sqlex.Number = 50000 Then
                            MessageWindow.ShowMessage("Can't Limite this Specification since it is use for an Item Master Test.")
                        Else
                            MessageWindow.ShowMessage(sqlex)
                        End If
                    Finally
                        If sqlcmd IsNot Nothing Then
                            sqlcmd.Connection.Close()
                            sqlcmd.Dispose()
                        End If
                    End Try
                Else
                    MessageWindow.ShowMessage("No need to Limite, this Specification is not reference more than once.")
                End If

                'End If
            End If
        End If
    End Sub

    Public Overridable Sub SpecRevDetail_Revise(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()

            If aRow IsNot Nothing Then

                If CInt(aRow("NbReference")) > 1 Then
                    'If CBool((aRow("IsCopy"))) Then

                    Dim ItemMasterSpecRevDetailID As Guid = CType(aRow("ItemMasterSpecRevDetailID"), Guid)
                    Dim ItemMasterSpecID As Guid = CType(aRow("ItemMasterSpecID"), Guid)
                    Dim ItemMasterSpecRevID As Guid = CType(aRow("ItemMasterSpecRevID_FK"), Guid)

                    'TODO...
                    Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

                    Try
                        sqlcmd = MetaQuery.GetSPCmdByMetaName("ItemMasterSpecificationRevisionDetail_Revise")
                        'Match les parametres de la SP avec les colonne de la grilles
                        For Each pr As System.Data.SqlClient.SqlParameter In sqlcmd.Parameters
                            If aRow.Table.Columns.Contains(pr.SourceColumn) Then
                                sqlcmd.Parameters(pr.ParameterName).Value = aRow(pr.SourceColumn)
                            End If
                        Next
                        sqlcmd.ExecuteNonQuery()
                        aGridControl.ReloadGrid()
                        'Fin TODO
                    Catch sqlex As System.Data.SqlClient.SqlException
                        If sqlex.Number = 50000 Then
                            MessageWindow.ShowMessage("Can't Revise this Specification since it is use for an Item Master Test.")
                        Else
                            MessageWindow.ShowMessage(sqlex)
                        End If
                    Finally
                        If sqlcmd IsNot Nothing Then
                            sqlcmd.Connection.Close()
                            sqlcmd.Dispose()
                        End If
                    End Try
                End If
            End If
        End If
    End Sub

    Public Overridable Sub SpecRevDetail_GenerateCOAQuery(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()

            If aRow IsNot Nothing Then
                Try
                    'SystemBoxSDK.PL.MESSDK.CertificateOfAnalysis_PL.GenerateCOAQuery(imExplorer.ItemMasterRevID, DfltSocietyID, Nothing)
                    MessageWindow.ShowMessage("Succesfully Generate COA Query.")
                Catch sqlex As System.Data.SqlClient.SqlException
                    If sqlex.Number = 50000 Then
                        MessageWindow.ShowMessage("Can't Generate COA Query.")
                    Else
                        MessageWindow.ShowMessage(sqlex)
                    End If
                End Try
            End If

        End If
    End Sub

    Public Overridable Sub SpecRevDetail_ShownMasterEditor(sender As Object, e As System.EventArgs)
        Dim aView As GridView = CType(sender, GridView)
        Dim aRow As DataRow = aView.GetFocusedDataRow()
        Dim SpecificationID As Guid
        Dim SpecRevision As Integer
        Dim edit As GridLookUpEdit

        If TypeOf aView.ActiveEditor Is GridLookUpEdit Then
            edit = CType(aView.ActiveEditor, GridLookUpEdit)
            edit.Properties.View.ActiveFilterEnabled = False

            If aView.FocusedColumn.FieldName = "SpecID_FK" And Not aView.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                'Ici on filtre LOV_Specification pour qu'il n'affiche que les Spec Active

                edit.Properties.View.ActiveFilterString = "Inactive = False"
                edit.Properties.View.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.Never

            ElseIf aView.FocusedColumn.FieldName = "RoutingID_FK" And Not aView.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                'Ici on filtre LOV_IMRouting pour qu'il n'affiche que les Routing appartenant a la meme revision de Item Master


                edit.Properties.View.ActiveFilterString = String.Format("ItemMasterRevID = '{0}' ", NodeDataRow("ParentID").ToString.Substring(0, 36))
                edit.Properties.View.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.Never

            ElseIf aView.FocusedColumn.FieldName = "SpecificationTestRevId_FK" And Not aView.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                'Ici on filtre LOV_SpecTest pour qu'il n'affiche que les Test de la Spec choisie

                If aRow Is Nothing Then
                    SpecificationID = Guid.Empty
                Else
                    SpecificationID = If(IsDBNull(aRow("SpecID_FK")), Guid.Empty, CType(aRow("SpecID_FK"), Guid))
                    SpecRevision = If(IsDBNull(aRow("MaxSpecRevision")), 0, CInt(aRow("MaxSpecRevision")))
                End If

                edit.Properties.View.ActiveFilterString = String.Format("IsActivated = True and RevisionNumber = {0} and SpecificationId_FK = '{1}' ", SpecRevision, SpecificationID.ToString)
                edit.Properties.View.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.Never
            End If

        End If
    End Sub





#Region "Spec Value"
    ''' <summary>
    ''' This Sub create and assign the proper LOV for the Spec selected if the psec is marked with a list
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Overridable Sub SpecRevDetail_CreateSpecValueLOV(ByVal sender As Object, ByVal e As CustomRowCellEditEventArgs)
        Dim aDetailview As GridView = DirectCast(sender, GridView)
        Dim aRow As DataRow = aDetailview.GetFocusedDataRow()

        If aRow IsNot Nothing Then
            If aRow("SpecList") IsNot DBNull.Value AndAlso CBool(aRow("SpecList")) Then

                Dim aEdit As New RepositoryItemCheckedComboBoxEdit
                Dim SpecID As Guid
                Dim sqlWhere As String

                If aRow IsNot Nothing AndAlso Not IsDBNull(aRow("SpecID_FK")) Then
                    SpecID = If(IsDBNull(aRow), Guid.Empty, CType(aRow("SpecID_FK"), Guid))
                Else
                    SpecID = Guid.Empty
                End If

                sqlWhere = String.Format("SpecID_FK = '{0}'", SpecID)
                aEdit = CheckComboBuilder("LOVCB_SpecificationValues", sqlWhere, Nothing, Nothing)
                aEdit.Name = "LOVCB_SpecificationValues"

                e.RepositoryItem = aEdit

            End If
        End If

    End Sub

#End Region





#End Region

#Region "Context menu"

    Private Sub RoutingSheetDiagram(ByVal sender As Object, ByVal e As EventArgs)
        Dim binarydata() As Byte
        Dim binaryStream As IO.MemoryStream = Nothing
        Dim aMetaGraphForm As MetaGraphForm
        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)

        If view IsNot Nothing Then
            Dim aRow As DataRow = view.GetFocusedDataRow()
            If aRow IsNot Nothing Then
                aMetaGraphForm = New MetaGraphForm()
                aMetaGraphForm.MetaControlCd = Me.PanelName
                aMetaGraphForm.Id = CType(aRow("RoutingSheetID"), Guid)
                '
                If Not IsDBNull(aRow("BinaryDiagram")) Then
                    binaryStream = New IO.MemoryStream()
                    binarydata = CType(aRow("BinaryDiagram"), Byte())
                    binaryStream.Write(binarydata, 0, binarydata.Length)
                    binaryStream.Position = 0
                    aMetaGraphForm.DocumentStream = binaryStream
                End If
                '
                'If CBool(aDataRowSOPRev("IsActivated")) = True Then
                '    aMetaGraphForm.ActivatedDocument = True
                'End If
                '
                'AddHandler aMetaGraphForm.SaveToDataBase, AddressOf SaveToDataBase
                aMetaGraphForm.ShowDialog()
                aGridControl.ReloadGrid()
            End If
        End If
    End Sub




    Public Overridable Sub MenuNewItemMaster(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        PL = New SystemBoxSDK.PL.MESSDK.ItemMaster_PL("ItemMaster")
        'Tip: Trick to have only the Table columns definition
        PL.SQLWhere = "1 = 2"
        aGridControl = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = PL}
        AddHandler aGridControl.InitNewMasterRow, AddressOf ItemMaster_InitNewMasterRow

        For Each aFrm As XtraForm In Me.ParentForm.MdiChildren
            If aFrm.Name = PanelName Then
                aFrm.Controls.Clear()
                aFrm.Controls.Add(aGridControl)
                aFrm.Text = aGridControl.Pl.QueryName
                aFrm.Show()
            End If
            aFrm.Refresh()
        Next

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuNewItemMasterRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        If NodeDataRow IsNot Nothing Then
            imExplorer = New IMExplorerNodeInfo(NodeDataRow)
            Try
                SystemBoxSDK.PL.MESSDK.ItemMasterRevision_PL.CreateNewItemMaster(imExplorer.NodeID)
                ReloadTree()
            Catch ex As Exception
                MessageWindow.ShowMessage(ex)
            End Try
        End If

        Me.Cursor = Cursors.Default
    End Sub


    Public Overridable Sub MenuApproveItemMasterRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_Approve")

            sqlcmd.Parameters("@ItemMasterRevID").Value = imExplorer.NodeID
            sqlcmd.Parameters("@Username").Value = AppManager.UserName

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuActivateItemMasterRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor


        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_Activate")

            sqlcmd.Parameters("@ItemMasterRevID").Value = imExplorer.NodeID
            sqlcmd.Parameters("@Username").Value = AppManager.UserName

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try


        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuUnActivateItemMasterRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_UnActivate")

            sqlcmd.Parameters("@ItemMasterRevID").Value = imExplorer.NodeID

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try


        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuDeleteItemMasterRevision(ByVal sender As Object, ByVal e As EventArgs)
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Me.Cursor = Cursors.WaitCursor

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_Delete")
            sqlcmd.Parameters("@ItemMasterRevID").Value = imExplorer.NodeID

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As Exception
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try


        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuCopyToNewItemMasterRevision(ByVal sender As Object, ByVal e As EventArgs)
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Me.Cursor = Cursors.WaitCursor

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_CopyFrom")

            sqlcmd.Parameters("@ItemMasterRevId").Value = imExplorer.NodeID
            sqlcmd.Parameters("@ItemMasterID_FK").Value = imExplorer.ParentID

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try


        Me.Cursor = Cursors.Default
    End Sub


    Public Overridable Sub MenuCopyToAnotherItemMasterRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Dim gridSP As GridExtSP = New GridExtSP("IMRevision_CopyToAnother") With {.Dock = DockStyle.Fill}
        gridSP.SaveCMD = AddressOf CopyToAnotherItemMasterRevision
        AddHandler gridSP.AfterLoad, AddressOf AddRowParameter
        'gridSP.FormCtrlCD = PanelName
        'gridSP.SecureGrid = False


        Dim aFrm As XtraForm = New XtraForm()
        If gridSP IsNot Nothing Then
            aFrm.MdiParent = Me.ParentForm
            aFrm.Controls.Add(gridSP)
            aFrm.Text = "Copy To Another Item Master" 'imExplorer.Prd_CD_Descr_PRM + " (Rev. " + imExplorer.IMLabelNumber + ")"
            aFrm.Show()
            aFrm.Focus()
        End If

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Function CopyToAnotherItemMasterRevision(ByVal aMetaDataTable As MetaDataTable) As Boolean
        Try
            aMetaDataTable.ApplyChanges(continueUpdateOnError:=False, reload:=False)
            MessageWindow.ShowMessage("Successfully Copied.", MsgBoxStyle.Information)
            ReloadTree()
        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        End Try
        Return True
    End Function

    Public Overridable Sub MenuEnableSpecEditing(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_EnableSpecification")
            sqlcmd.Parameters("@ItemMasterRevId").Value = imExplorer.NodeID

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuEnableRoutingEditing(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_EnableRouting")
            sqlcmd.Parameters("@ItemMasterRevId").Value = imExplorer.NodeID

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuEnableBOMEditing(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMRevision_EnableBOM")
            sqlcmd.Parameters("@ItemMasterRevId").Value = imExplorer.NodeID

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuActivateBOMRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("BOMRevision_Activate")

            sqlcmd.Parameters("@BOMRevID").Value = imExplorer.NodeID
            'sqlcmd.Parameters("@Set").Value = 1

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuActivateRoutingRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("RoutingRevision_Activate")

            sqlcmd.Parameters("@RoutingRevID").Value = imExplorer.NodeID
            'sqlcmd.Parameters("@Set").Value = 1

            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuActivateSpecRevision(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("IMSpecRevision_Activate")

            sqlcmd.Parameters("@IMSpecRevID").Value = imExplorer.NodeID
            sqlcmd.Parameters("@Set").Value = 1


            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            ReloadTree()
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub


    Private Sub MenuNewSite()
        MessageWindow.ShowMessage("comming on next release")
    End Sub

    Private Sub MenuPrintBOM()
        MessageWindow.ShowMessage("comming on next release")
    End Sub

    Private Sub MenuPrintRouting()
        MessageWindow.ShowMessage("comming on next release")
    End Sub


    ''' <summary>
    ''' This sub handle the Print menu for Specification
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Overridable Sub MenuPrintSpecification(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Dim queryName As String = "ItemMasterSpecification_Report"
        Dim reportName As String = "ItemMasterSpecification_Report"

        Using mquery As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            If mquery IsNot Nothing Then
                Dim report As DevExpress.XtraReports.UI.XtraReport = SCIEF.ActiveFramework.CommonExt.RptNotification.GetReportFromDB(reportName)
                If report IsNot Nothing Then

                    mquery.SQLWhere = mquery.SQLWhere + String.Format("IMSR.ItemMasterSpecRevID = '{0}'", imExplorer.NodeID)

                    mquery.FillResultQuery()
                    report.DataSource = mquery.ResultQuery
                    report.CreateDocument()

                    Dim aFrm As Form = New ReportPrintForm() With {.Text = "Print Invoice", .Report = report}
                    aFrm.Show()
                Else
                    Console.WriteLine(String.Format("{0}, Not Found in Report Definition. Notification abord", reportName))
                End If
            Else
                Console.WriteLine(String.Format("{0}, Not Found in MetaCommand. Notification abord", queryName))
            End If
        End Using

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub MenuRefreshCOAQuery(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Dim view As GridView = CType(aGridControl.GridControl1.FocusedView, GridView)
        Dim aRow As DataRow = view.GetFocusedDataRow()
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

        Try
            If aRow IsNot Nothing Then
                sqlcmd = MetaQuery.GetSPCmdByMetaName("COA_RefreshMetaQuery")

                sqlcmd.Parameters("@ItemMasterRevID").Value = Guid.Parse(aRow("ItemMasterRevID_FK").ToString)
                sqlcmd.Parameters("@SocietyID").Value = Guid.Parse(aRow("SocietyID_FK").ToString)
                sqlcmd.Parameters("@QueryID").Value = Guid.Parse(aRow("QueryID_FK").ToString)

                sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)

                MessageWindow.ShowMessage("COA Query Successfully Refreshed.", MsgBoxStyle.Information)
            End If
        Catch sqlex As System.Data.SqlClient.SqlException
            MessageWindow.ShowMessage(sqlex)
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try

        Me.Cursor = Cursors.Default
    End Sub

#End Region

    Public Overridable Sub AddRowParameter(sender As Object, e As System.EventArgs)
        Try
            Dim aGrid As GridExtSP = CType(sender, GridExtSP)

            Dim arow As DataRow = aGrid.MetaDataTable.NewRow()
            'assign value for the metacolumn here

            arow("@ItemMasterRevID") = imExplorer.NodeID

            aGrid.MetaDataTable.Rows.Add(arow)

        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        End Try
    End Sub

#Region "Utils"
    Public formatType As DevExpress.Utils.FormatType

    Public Overridable Function CheckComboBuilder(ByVal queryName As String, ByVal sqlWhere As String, ByVal sqlFrom As String, ByVal filter As String) As RepositoryItemCheckedComboBoxEdit
        Dim aEdit As RepositoryItemCheckedComboBoxEdit
        Dim hideCol As Boolean
        Dim colname As String

        Using mq As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            If Not String.IsNullOrWhiteSpace(sqlWhere) Then
                mq.SQLWhere = sqlWhere
            End If
            '

            'ICI Le DataField filter appliquer quand on a la securité
            If Not String.IsNullOrWhiteSpace(sqlFrom) Then
                mq.SQLFrom = String.Concat(mq.SQLFrom, sqlFrom)
            End If

            If Not String.IsNullOrWhiteSpace(filter) Then
                mq.SQLWhere = String.Concat(mq.SQLWhere, filter)
            End If
            '
            mq.FillResultQuery()
            aEdit = New RepositoryItemCheckedComboBoxEdit() With {.DataSource = mq.ResultQuery _
                                                                 , .DisplayMember = mq.ResultQuery.Columns(CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex).ToString _
                                                                 , .ValueMember = mq.ResultQuery.Columns(CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex).ToString _
                                                                 , .PopupFormSize = New Size(300, 300), .NullText = "(none)"}

            For Each row As DataRow In mq.MetaColumns.Rows
                colname = row("ColumnName").ToString
                hideCol = False
                If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                    If colname.EndsWith("_ALT") Then
                        hideCol = True
                    End If
                Else
                    If colname.EndsWith("_PRM") Then
                        hideCol = True
                    End If
                End If

            Next
            aEdit.DataSource = mq.ResultQuery
            Return aEdit
        End Using
    End Function

    Public Overridable Function LOVBuilder(ByVal queryName As String, ByVal sqlWhere As String, ByVal sqlFrom As String, ByVal filter As String) As RepositoryItemGridLookUpEdit
        Dim aEdit As RepositoryItemGridLookUpEdit
        Dim colVisible As Boolean
        Dim hideCol As Boolean
        Dim colname As String
        Dim Column As DevExpress.XtraGrid.Columns.GridColumn
        Dim view As Views.Base.ColumnView

        Using mq As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            If Not String.IsNullOrWhiteSpace(sqlWhere) Then
                mq.SQLWhere = sqlWhere
            End If
            '

            'ICI Le DataField filter appliquer quand on a la securité
            If Not String.IsNullOrWhiteSpace(sqlFrom) Then
                mq.SQLFrom = String.Concat(mq.SQLFrom, sqlFrom)
            End If

            If Not String.IsNullOrWhiteSpace(filter) Then
                mq.SQLWhere = String.Concat(mq.SQLWhere, filter)
            End If
            '
            mq.FillResultQuery()
            aEdit = New RepositoryItemGridLookUpEdit() With {.DataSource = mq.ResultQuery, .DisplayMember = mq.ResultQuery.Columns(CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex).ToString, .ValueMember = mq.GUIDField, .PopupFormSize = New Size(800, 300), .NullText = "(none)"}
            aEdit.View.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
            aEdit.View.OptionsView.ColumnAutoWidth = False
            aEdit.View.OptionsView.ShowAutoFilterRow = True
            aEdit.View.OptionsBehavior.ReadOnly = True
            view = aEdit.View
            view.Columns.Clear()
            For Each row As DataRow In mq.MetaColumns.Rows
                colname = row("ColumnName").ToString
                hideCol = False
                If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                    If colname.EndsWith("_ALT") Then
                        hideCol = True
                    End If
                Else
                    If colname.EndsWith("_PRM") Then
                        hideCol = True
                    End If
                End If
                If hideCol = False Then
                    colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
                    Column = view.Columns.AddField(colname)
                    Column.VisibleIndex = CInt(row("pOrder"))
                    Column.Caption = row("pCaption").ToString
                    Column.Visible = colVisible
                    Column.Width = CInt(row("pWidth"))
                    Column.ToolTip = row("pToolTip").ToString

                    formatType = GetFormatType(row)
                    '
                    Column.DisplayFormat.FormatType = formatType
                    Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
                End If
            Next
            aEdit.DataSource = mq.ResultQuery
            Return aEdit
        End Using
    End Function


    Public Shared Function GetFormatType(ByVal arow As DataRow) As DevExpress.Utils.FormatType
        If (Not String.IsNullOrEmpty(arow("pNumberFormatID_FK").ToString)) Then
            Select Case CType(arow("pNumberFormatID_FK"), Guid)

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_CURRENCY, CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALNUMBER, CommonExt.Base.IdRepository.META_NUMBERFORMAT_PERCENT, CommonExt.Base.IdRepository.META_NUMBERFORMAT_STANDARD, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SCIENTIFIC
                    Return DevExpress.Utils.FormatType.Numeric

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTTIME
                    Return DevExpress.Utils.FormatType.DateTime

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_FORMATEXPR
                    Return DevExpress.Utils.FormatType.Custom

                Case Else
                    Return DevExpress.Utils.FormatType.None
            End Select
        Else
            Return DevExpress.Utils.FormatType.None
        End If
    End Function

#End Region

    Public Overridable Sub InDev(ByVal sender As Object, ByVal e As EventArgs)
        MessageWindow.ShowMessage("En développement")
    End Sub


End Class

''' <summary>
''' Class pour identidfier a partir de la datarow les champs que nous avons pour la Meta IMExplorer
''' </summary>
''' <remarks>le design de cela consite en : 
''' pour aider dans le navigation du tree view.
''' nous avoins besoin de trouver une facon de savoir qua nd on click sur un noeud de la grid qui resemble a un treview de quossé qui faut passer 
''' a la form a coté pour que le Gridextpl pouisse scoper l'info </remarks>
Public Class IMExplorerNodeInfo
    Inherits CommonExt.Utils.ExplorerNodeInfo

    ' Public Property SiteCd As String
    'Public Property Prd_CD_Descr_ALT As String
    'Public Property Prd_CD_Descr_PRM As String
    'Public Property PrdCD As String

    Public Property LabelNumber As String
    Public Property LabelNumberDisplay As String
    Public Property ApprouvedBy As String
    Public Property IMRevisionApproved As Boolean

    Public Property SectionRevisionNumber As String
    Public Property SectionRevisionNumberDisplay As String
    Public Property SectionActivated As Boolean

    'Public Property SiteId As Guid
    Public Property ItemMasterID As Guid
    Public Property ItemMasterRevID As Guid
    'Public Property IMSectionRev As String
    Public Property PrdID As Guid

    Public Property BOMEnabled As Boolean
    Public Property RoutingEnabled As Boolean
    Public Property SpecEnabled As Boolean


    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal datarow As DataRow)
        MyBase.New(datarow)
    End Sub


    Public Overrides Sub Assign(ByVal datarow As DataRow)
        MyBase.Assign(datarow)

        If Not IsDBNull(NodeDataRow("BOMEnabled")) Then
            BOMEnabled = CBool(datarow("BOMEnabled"))
        End If

        If Not IsDBNull(NodeDataRow("RoutingEnabled")) Then
            RoutingEnabled = CBool(datarow("RoutingEnabled"))
        End If

        If Not IsDBNull(NodeDataRow("SpecEnabled")) Then
            SpecEnabled = CBool(datarow("SpecEnabled"))
        End If

        If Not IsDBNull(NodeDataRow("ItemMasterID")) Then
            ItemMasterID = CType(datarow("ItemMasterID"), Guid)
        End If

        If NodeDataRow.Table.Columns.Contains("ItemMasterRevisionID") Then
            If Not IsDBNull(NodeDataRow("ItemMasterRevisionID")) Then
                ItemMasterRevID = CType(datarow("ItemMasterRevisionID"), Guid)
            End If
        End If

        If NodeDataRow.Table.Columns.Contains("ApprovedBy") Then
            If Not IsDBNull(NodeDataRow("ApprovedBy")) Then
                IMRevisionApproved = True
            Else
                IMRevisionApproved = False
            End If
        End If

        If Not IsDBNull(NodeDataRow("PrdID")) Then
            PrdId = CType(datarow("PrdID"), Guid)
        End If

    End Sub

End Class

